package cn.you.GenghisKhan.common.boot;
import cn.you.GenghisKhan.common.extension.ExtensionLoader;
import cn.you.GenghisKhan.common.utils.PropertyUtil;
import cn.you.GenghisKhan.config.ConfigCentre;
import cn.you.GenghisKhan.config.bean.AppBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;

import java.util.HashMap;
import java.util.Map;
public class SpringApplication {
    private static final Logger logger = LoggerFactory.getLogger(SpringApplication.class);
    public static void run(Class<?> source,String... args)
    {
        org.springframework.boot.SpringApplication
                springApplication
                = getSpringApplication(source);
        if(springApplication!=null)
        {
            springApplication.run();
        }
        else
        {
            logger.error("配置错误，找不到应用：{}的配置", PropertyUtil.getProperty("app.name"));
        }

    }
    public static void run(Class<?> source)
    {
        org.springframework.boot.SpringApplication
                springApplication
                = getSpringApplication(source);
        if(springApplication!=null)springApplication.run();
    }
    private static org.springframework.boot.SpringApplication getSpringApplication(Class<?> source) {
        AppBean appbean = ExtensionLoader.getExtensionLoader(ConfigCentre.class).getAdaptiveExtension().getAppBean();

            org.springframework.boot.SpringApplication application = new org.springframework.boot.SpringApplication(source);
            application.setBannerMode(Banner.Mode.OFF);
            application.setLogStartupInfo(false);
        if (appbean != null&&appbean.getAppName()!=null&&appbean.getTomcatPort()!=null) {
            Map<String, Object> pro = new HashMap<String, Object>();
            pro.put("server.port", appbean.getTomcatPort());
            pro.put("server.tomcat.maxConnections", appbean.getTomcatMaxconnections());
            pro.put("server.tomcat.acceptCount", appbean.getTomcatAcceptcount());
            pro.put("server.tomcat.maxThreads ", appbean.getTomcatMaxthreads());
            pro.put("server.tomcat.minSpareThreads", appbean.getTomcatMinsparethreads());
            pro.put("server.connectionTimeout", appbean.getTomcatConnectiontimeout());
            pro.put("spring.http.encoding.force", true);
            pro.put("spring.http.encoding.charset", "UTF-8");
            pro.put("spring.http.encoding.enabled", true);
            pro.put("server.tomcat.uri-encoding", "UTF-8");
            pro.put("server.contextPath", "/" + "");
            application.setDefaultProperties(pro);

        }
        else
        {
            application.setWebEnvironment(false);
        }
        return application;
    }
}
